﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using CommunitySystem.EmpbasicService;
using CommunitySystem.GuaZhiDuanLianService;
using CommunitySystem.Views;
using EHR.Common;

namespace CommunitySystem
{
    public partial class GuaZhiQiManControl : UserControl
    {
        private EmpbasicService.EmpBasicServiceClient Client = new EmpbasicService.EmpBasicServiceClient();
        public ObservableCollection<EmpbasicService.OrgForHRModel> OrgList =
            new ObservableCollection<EmpbasicService.OrgForHRModel>();
        ObservableCollection<EmpbasicService.OrgForHRModel> forumList = new ObservableCollection<EmpbasicService.OrgForHRModel>();
        public ObservableCollection<GuaZhiEmpModel> selectedempmodel =
            new ObservableCollection<GuaZhiEmpModel>();
        private GuaZhiDuanLianServiceClient Client1 =
            new GuaZhiDuanLianServiceClient();
        public GuaZhiQiManControl()
        {
            InitializeComponent();
            ListBoxOfLife.Items.Clear();
            Client.GetDengLuJueSeCompleted += new EventHandler<EmpbasicService.GetDengLuJueSeCompletedEventArgs>(Client_GetDengLuJueSeCompleted);
            Client.GetDengLuJueSeAsync(Session.LoginUser.LoginName);
            Client.GetOrgForHRModelCompleted += new EventHandler<EmpbasicService.GetOrgForHRModelCompletedEventArgs>(Client_GetOrgForHRModelCompleted);
            Client.GetOrgForHRModelbyIDsCompleted += new EventHandler<EmpbasicService.GetOrgForHRModelbyIDsCompletedEventArgs>(Client_GetOrgForHRModelbyIDsCompleted);
            Client.GetDengLuOrgCompleted += new EventHandler<GetDengLuOrgCompletedEventArgs>(Client_GetDengLuOrgCompleted);
            Client1.GetGuaZhiDuanLianEmpModelCompleted += new EventHandler<GetGuaZhiDuanLianEmpModelCompletedEventArgs>(Client1_GetGuaZhiDuanLianEmpModelCompleted);
            Client1.GetGuaZhiDuanLianEmpZongModelCompleted +=
                new EventHandler<GetGuaZhiDuanLianEmpZongModelCompletedEventArgs>(Client1_GetGuaZhiDuanLianEmpZongModelCompleted);
            Client1.GetGuaZhiDuanLianJiHuaModelCompleted += new EventHandler<GetGuaZhiDuanLianJiHuaModelCompletedEventArgs>(Client1_GetGuaZhiDuanLianJiHuaModelCompleted);
            Client1.GetGuaZhiDuanLianJiHuaModelAsync(0, "0", 0);
            Client1.GetGuaZhiDuanLianJiHuaModelForComCompleted +=
                new EventHandler<GetGuaZhiDuanLianJiHuaModelForComCompletedEventArgs>(Client1_GetGuaZhiDuanLianJiHuaModelForComCompleted);
            Client1.GetGuaZhiDuanLianJiHuaModelForComAsync("");
            _gridClickManagerXQ = new MouseClickManager(DGRole, 300);
            _gridClickManagerXQ.DoubleClick += new System.Windows.Input.MouseButtonEventHandler(_gridClickManagerXQ_DoubleClick);
        }
        private void _gridClickManagerXQ_DoubleClick(object sender, MouseButtonEventArgs e)
        {
        }
        void Client1_GetGuaZhiDuanLianJiHuaModelForComCompleted(object sender, GetGuaZhiDuanLianJiHuaModelForComCompletedEventArgs e)
        {
            biaoti.ItemsSource = e.Result;
            if (e.Result != null && e.Result.Count > 0)
                biaoti.SelectedIndex = 0;
        }

        #region 获得组织机构树
        void Client_GetOrgForHRModelCompleted(object sender, EmpbasicService.GetOrgForHRModelCompletedEventArgs e)
        {
            OrgList = e.Result;
            forumList.Clear();
            foreach (EmpbasicService.OrgForHRModel i in e.Result)
            {
                forumList.Add(i);
            }
            AddTreeNode("全部单位", null);
        }

        private void AddTreeNode(string type, TreeViewItem treeViewItem)
        {
            List<EmpbasicService.OrgForHRModel> result = (from forumInfo in forumList
                                                          where forumInfo.Type == type
                                                          select forumInfo).ToList<EmpbasicService.OrgForHRModel>();

            if (result.Count > 0)
            {
                foreach (EmpbasicService.OrgForHRModel foruminfo in result)
                {
                    TreeViewItem objTreeNode = new TreeViewItem();

                    //StackPanel sp = new StackPanel();
                    CheckBox cb = new CheckBox();
                    cb.Content = foruminfo.Name;
                    cb.Tag = objTreeNode;
                    cb.DataContext = foruminfo;
                    //sp.Children.Add(cb);
                    cb.Click += new RoutedEventHandler(cb_Checked);
                    objTreeNode.Header = cb;
                    //objTreeNode.Header = foruminfo.Name;
                    //objTreeNode.DataContext = foruminfo;
                    //objTreeNode.Tag = foruminfo.ID;
                    if ((objTreeNode.Header as CheckBox).Content.ToString() == "组织机构") objTreeNode.IsExpanded = true;

                    //此样式将会添加的所有叶子结点上
                    //objTreeNode.ItemContainerStyle = this.Resources["RedItemStyle"] as Style;

                    //添加根节点
                    if (treeViewItem == null)
                    {
                        TreeOfLife.Items.Add(objTreeNode);
                    }
                    else
                    {
                        treeViewItem.Items.Add(objTreeNode);
                    }
                    AddTreeNode(foruminfo.Name, objTreeNode);
                }
            }
        }
        public int orgid { get; set; }
        public List<string> orgids = new List<string>();
        public string type { get; set; }
        void cb_Checked(object sender, RoutedEventArgs e)
        {
            CheckBox cb = sender as CheckBox;
            EmpbasicService.OrgForHRModel rm = cb.DataContext as EmpbasicService.OrgForHRModel;
            if (cb.IsChecked == true)
            {
                //if (orgids != null)
                //{
                //orgid = Convert.ToInt32(((EmpbasicService.OrgForHRModel)cb.DataContext).ID);
                //tbTitle.Text = cb.Content.ToString();
                if (!orgids.Contains(((EmpbasicService.OrgForHRModel)cb.DataContext).ID.ToString()))
                    orgids.Add(((EmpbasicService.OrgForHRModel)cb.DataContext).ID.ToString());
                string ss = "";
                foreach (string i in orgids)
                    ss += i + ",";
                if (string.IsNullOrEmpty(ss) || orgids.Contains("79")) ss = "0";
                else ss = ss.Substring(0, ss.Length - 1);
                LoadData(ss);
                CheckChildItem(cb.Tag as TreeViewItem);
            }
            else
            {
                //if (orgids != null)
                //{
                if (orgids != null)
                {
                    if (orgids.Contains(((EmpbasicService.OrgForHRModel)cb.DataContext).ID.ToString()))
                        orgids.Remove(((EmpbasicService.OrgForHRModel)cb.DataContext).ID.ToString());
                }
                string ss = "";
                foreach (string i in orgids)
                    ss += i + ",";
                if (ss.Length > 1) ss = ss.Substring(0, ss.Length - 1);
                LoadData(ss);
                UnCheckChildItem(cb.Tag as TreeViewItem);
            }
        }

        void CheckChildItem(TreeViewItem item)
        {
            foreach (TreeViewItem tvi in item.Items)
            {
                if (tvi != null)
                {
                    CheckBox cb = tvi.Header as CheckBox;
                    cb.IsChecked = true;
                    if (!orgids.Contains(((EmpbasicService.OrgForHRModel)cb.DataContext).ID.ToString()))
                        orgids.Add(((EmpbasicService.OrgForHRModel)cb.DataContext).ID.ToString());
                    CheckChildItem(tvi);
                }
            }
        }
        void UnCheckChildItem(TreeViewItem item)
        {
            foreach (TreeViewItem tvi in item.Items)
            {
                if (tvi != null)
                {
                    CheckBox cb = tvi.Header as CheckBox;
                    cb.IsChecked = false;
                    if (orgids.Contains(((EmpbasicService.OrgForHRModel)cb.DataContext).ID.ToString()))
                        orgids.Remove(((EmpbasicService.OrgForHRModel)cb.DataContext).ID.ToString());
                    UnCheckChildItem(tvi);
                }
            }
        }
        #endregion
        #region 左右拖动的条
        private GridLength _lastColLeftLength;
        private GridLength _lastColRightLength;
        private void GridSpliteTo_ToLeft(object sender, EventArgs e)
        {
            //已经到最左边，直接返回
            if (colLeft.Width.Value == 0.0)
            {
                return;
            }

            //
            if (colRight.Width.Value == 0)
            {
                colLeft.Width = _lastColLeftLength;
                colRight.Width = _lastColRightLength;
            }
            else
            {
                _lastColLeftLength = colLeft.Width;
                _lastColRightLength = colRight.Width;

                colLeft.Width = new GridLength(0);
                colRight.Width = new GridLength(150, GridUnitType.Star);
            }
        }

        private void GridSpliteTo_ToRight(object sender, EventArgs e)
        {
            if (colRight.Width.Value == 0)
            {
                return;
            }

            if (colLeft.Width.Value == 0)
            {
                colLeft.Width = _lastColLeftLength;
                colRight.Width = _lastColRightLength;
            }
            else
            {
                _lastColLeftLength = colLeft.Width;
                _lastColRightLength = colRight.Width;

                colRight.Width = new GridLength(0);
                colLeft.Width = new GridLength(300, GridUnitType.Star);
            }
        }
        #endregion
        private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            orgid = Convert.ToInt32(((OrgForHRModel)(ListBoxOfLife.SelectedItem)).ID);
            orgids.Clear();
            orgids.Add(orgid.ToString());
            LoadData(orgids[0]);
        }

        void Client_GetOrgForHRModelbyIDsCompleted(object sender, EmpbasicService.GetOrgForHRModelbyIDsCompletedEventArgs e)
        {
            ListBoxOfLife.ItemsSource = e.Result;
            ListBoxOfLife.SelectedIndex = 0;
            orgid = Convert.ToInt32(e.Result[0].ID);
            orgids.Clear();
            orgids.Add(orgid.ToString());
            LoadData(orgids[0]);
        }

        private string juese = "";
        void Client_GetDengLuJueSeCompleted(object sender, EmpbasicService.GetDengLuJueSeCompletedEventArgs e)
        {
            juese = e.Result;
            if (e.Result != "人事干部")
            {
                if (TreeOfLife.ItemsSource != null) TreeOfLife.ItemsSource = null;
                TreeOfLife.Visibility = System.Windows.Visibility.Visible;
                ListBoxOfLife.Visibility = System.Windows.Visibility.Collapsed;
                Client.GetOrgForHRModelAsync(0);
                LoadData("0");
            }
            else
            {
                TreeOfLife.Visibility = System.Windows.Visibility.Collapsed;
                ListBoxOfLife.Visibility = System.Windows.Visibility.Visible;
                Client.GetDengLuOrgAsync(Session.LoginUser.LoginName);
            }
        }
        public String[] Oldorgids;
        void Client_GetDengLuOrgCompleted(object sender, EmpbasicService.GetDengLuOrgCompletedEventArgs e)
        {
            if (!string.IsNullOrEmpty(e.Result))
            {
                Oldorgids = e.Result.Split(',');
            }
            Client.GetOrgForHRModelbyIDsAsync("(" + e.Result + ")");
        }
        private void ChaData_Click(object sender, RoutedEventArgs e)
        {
            string ss = "";
            foreach (string ii in orgids)
                ss += ii + ",";
            if (string.IsNullOrEmpty(ss)) ss = "0";
            else ss = ss.Substring(0, ss.Length - 1);
            LoadData(ss);
        }
        void Client1_GetGuaZhiDuanLianJiHuaModelCompleted(object sender, GetGuaZhiDuanLianJiHuaModelCompletedEventArgs e)
        {
            biaoti.ItemsSource = e.Result;
        }
        private string islock = "";
        private void CheckBox_Checked(object sender, RoutedEventArgs e)
        {
            biaoti.ItemsSource = null;
            islock = "已结束";
            Client1.GetGuaZhiDuanLianJiHuaModelAsync(0, islock, 0);
            Client1.GetGuaZhiDuanLianJiHuaModelForComAsync("已结束");
        }

        private void chkHiddenCols_Unchecked(object sender, RoutedEventArgs e)
        {
            biaoti.ItemsSource = null;
            islock = "";
            Client1.GetGuaZhiDuanLianJiHuaModelAsync(0, islock, 0);
            Client1.GetGuaZhiDuanLianJiHuaModelForComAsync("");
        }
        private int ExamID = 0;
        private string kaoshistatus = "";
        void gangwei_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (((ComboBox)sender).SelectedItem != null)
            {
                ExamID = ((GuaZhiDuanLianJiHuaModel)((((ComboBox)sender).SelectedItem))).ID;
                kaoshistatus =
                    ((GuaZhiDuanLianJiHuaModel)
                     ((((ComboBox)sender).SelectedItem))).Status;
                string ss = "";
                foreach (string ii in orgids)
                    ss += ii + ",";
                if (string.IsNullOrEmpty(ss)) ss = "0";
                else ss = ss.Substring(0, ss.Length - 1);
                LoadData(ss);
            }
            else ExamID = 0;
        }
        private ObservableCollection<GuaZhi_AttatchmentModel> _Attachment =
            new ObservableCollection<GuaZhi_AttatchmentModel>();
        private ObservableCollection<GuaZhi_AttatchmentModel> _Attachment1 =
            new ObservableCollection<GuaZhi_AttatchmentModel>();
        public void LoadData(string orgids)
        {
            Client1.GetGuaZhiDuanLianEmpZongModelAsync(ExamID, orgids, "'挂职中','挂职中-延期'", null);
        }
        private WrapPanel dgwp = null;
        private WrapPanel dgwp1 = null;
        private readonly MouseClickManager _gridClickManagerXQ;
        private void dgXQ_LoadingRow(object sender, DataGridRowEventArgs e)
        {
            e.Row.MouseLeftButtonUp += _gridClickManagerXQ.HandleClick;
            GuaZhiEmpModel bindData = (GuaZhiEmpModel)e.Row.DataContext;
            dgwp = DGRole.Columns[12].GetCellContent(e.Row).FindName("wp") as WrapPanel;
            dgwp1 = DGRole.Columns[13].GetCellContent(e.Row).FindName("wp") as WrapPanel;
            Init(bindData.ID);
        }
        private void Init(int id)
        {
            dgwp.Children.Clear();
            dgwp1.Children.Clear();
            HyperlinkButton hb = null;
            foreach (var item in _Attachment.Where(p => p.MainID == id).ToList())
            {
                hb = new HyperlinkButton() { Margin = new Thickness(10, 0, 0, 0), VerticalAlignment = VerticalAlignment.Center };
                hb.MouseLeftButtonDown += new MouseButtonEventHandler(hb_MouseLeftButtonDown);
                hb.Tag = item;
                hb.Content = item.realname;
                hb.Click += new RoutedEventHandler(hb_Click);
                dgwp.Children.Add(hb);

            }
            foreach (var item in _Attachment1.Where(p => p.MainID == id).ToList())
            {
                hb = new HyperlinkButton() { Margin = new Thickness(10, 0, 0, 0), VerticalAlignment = VerticalAlignment.Center };
                hb.MouseLeftButtonDown += new MouseButtonEventHandler(hb_MouseLeftButtonDown);
                hb.Tag = item;
                hb.Content = item.realname;
                hb.Click += new RoutedEventHandler(hb_Click);
                dgwp1.Children.Add(hb);

            }
        }
        void hb_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            //throw new NotImplementedException();
        }
        private List<byte> fileContent = new List<byte>();
        SaveFileDialog openFile;
        void hb_Click(object sender, RoutedEventArgs e)
        {
            HyperlinkButton hbtn = sender as HyperlinkButton;

            var attach = hbtn.Tag as GuaZhi_AttatchmentModel;

            SilverlightMessageBoxLibrary.CustomMessage cm = new SilverlightMessageBoxLibrary.CustomMessage("确认要下载此方案吗?", SilverlightMessageBoxLibrary.CustomMessage.MessageType.Confirm, null);
            cm.Show();
            cm.OKButton.Click += (sender1, e1) =>
            {
                string extend = attach.realname.Substring(attach.realname.LastIndexOf('.'));
                openFile = new SaveFileDialog() { Filter = string.Format("{0}|*.{0}", extend) };
                if (openFile.ShowDialog() == true)
                {
                    IsWorking.Visibility = Visibility.Visible;
                    tkbusy.BusyContent = "正在下载数据，请稍后...";

                    fileContent.Clear();
                    //Client2.DownLoadFileCompleted -= new EventHandler<PublicOfficialSelectionService.DownLoadFileCompletedEventArgs>(downLoadClient_DownLoadFileCompleted);
                    //Client2.DownLoadFileCompleted += new EventHandler<PublicOfficialSelectionService.DownLoadFileCompletedEventArgs>(downLoadClient_DownLoadFileCompleted);

                    //Client2.DownLoadFileAsync(new PublicOfficialSelectionService.DownLoadFile() { PathKey = "file", HasFinished = false, Lenght = 1600, FileName = attach.filename, StartPosition = 0 }, openFile.OpenFile());

                    CommunitySystem.JinShengService.JinShengServiceClient client = new JinShengService.JinShengServiceClient();
                    client.DownLoadFile1Completed -= new EventHandler<JinShengService.DownLoadFile1CompletedEventArgs>(client_DownLoadFile1Completed);
                    client.DownLoadFile1Completed += new EventHandler<JinShengService.DownLoadFile1CompletedEventArgs>(client_DownLoadFile1Completed);
                    client.DownLoadFile1Async(attach.filename);
                }

            };
        }

        void client_DownLoadFile1Completed(object sender, JinShengService.DownLoadFile1CompletedEventArgs e)
        {
            Stream myStream;
            if ((myStream = openFile.OpenFile()) != null)
            {
                using (BinaryWriter bw = new BinaryWriter(myStream))
                {

                    bw.Write(e.Result);
                    myStream.Dispose();
                    myStream.Close();
                    SilverlightMessageBoxLibrary.Message.InfoMessage("下载完毕!");
                    IsWorking.Visibility = Visibility.Collapsed;
                }

            }
        }
        void Client1_GetGuaZhiDuanLianEmpZongModelCompleted(object sender, GetGuaZhiDuanLianEmpZongModelCompletedEventArgs e)
        {
            _Attachment.Clear();
            _Attachment1.Clear();
            DGRole.ItemsSource = null;
            if (e.Result != null && e.Result.Count > 0)
            {
                for (int i = 0; i < e.Result.Count; i++)
                {
                    e.Result[i].Sec = i + 1;
                    foreach (var item in e.Result[i].Attachment.Where(p => p.Type == "小结材料"))
                    {
                        if (!_Attachment.Contains(_Attachment.Where(p => p.realname == item.realname && p.MainID == item.MainID && p.Type == "小结材料").FirstOrDefault()))
                            _Attachment.Add(item);
                    }
                    foreach (var item in e.Result[i].Attachment.Where(p => p.Type == "考核表"))
                    {
                        if (!_Attachment1.Contains(_Attachment.Where(p => p.realname == item.realname && p.MainID == item.MainID && p.Type == "考核表").FirstOrDefault()))
                            _Attachment1.Add(item);
                    }
                }
                DGRole.ItemsSource = e.Result;
            }
        }

        private void CheckData_Click(object sender, RoutedEventArgs e)
        {
            selectedempmodel.Clear();
            if (DGRole.ItemsSource != null)
            {
                foreach (GuaZhiEmpModel i in (ObservableCollection<GuaZhiEmpModel>)DGRole.ItemsSource)
                {
                    if (i.IsSelected == true && selectedempmodel.Where(p => p.ID == i.ID).FirstOrDefault() == null)
                    {
                        selectedempmodel.Add(i);
                    }
                    if (selectedempmodel.Where(p => p.ID == i.ID).FirstOrDefault() != null && i.IsSelected == false)
                    {
                        selectedempmodel.Remove(selectedempmodel.Where(p => p.ID == i.ID).FirstOrDefault());
                    }
                }
            }
            if (selectedempmodel.Count > 0)
            {
                string ids = "";
                foreach (GuaZhiEmpModel i in selectedempmodel)
                {
                    ids += i.ID + ",";
                }
                GuaZhiDuanLianDateWindow win = new GuaZhiDuanLianDateWindow(ids.Substring(0, ids.Length - 1), selectedempmodel[0].JiHuaID);
                win.Show();
                win.Closed += new EventHandler(win_Closed1);
            }
            else SilverlightMessageBoxLibrary.Message.ErrorMessage("请选择要结束的挂职信息！");
        }

        private void SaveShiJianData_Click(object sender, RoutedEventArgs e)
        {
            selectedempmodel.Clear();
            if (DGRole.ItemsSource != null)
            {
                foreach (GuaZhiEmpModel i in (ObservableCollection<GuaZhiEmpModel>)DGRole.ItemsSource)
                {
                    if (i.IsSelected == true && selectedempmodel.Where(p => p.ID == i.ID).FirstOrDefault() == null)
                    {
                        selectedempmodel.Add(i);
                    }
                    if (selectedempmodel.Where(p => p.ID == i.ID).FirstOrDefault() != null && i.IsSelected == false)
                    {
                        selectedempmodel.Remove(selectedempmodel.Where(p => p.ID == i.ID).FirstOrDefault());
                    }
                }
            }
            if (selectedempmodel.Count == 1)
            {
                GuaZhiQiManFuJianWindow win = new GuaZhiQiManFuJianWindow(selectedempmodel[0].ID);
                win.Show();
                win.Closed += new EventHandler(win_Closed);
            }
            else SilverlightMessageBoxLibrary.Message.ErrorMessage("只能选择一条信息上传附件！");
        }

        void win_Closed(object sender, EventArgs e)
        {
                string ss = "";
                foreach (string ii in orgids)
                    ss += ii + ",";
                if (string.IsNullOrEmpty(ss)) ss = "0";
                else ss = ss.Substring(0, ss.Length - 1);
                LoadData(ss);
           

        }

        void win_Closed1(object sender, EventArgs e)
        {
            if (((ChildWindow)sender).DialogResult == true)
            {
                SilverlightMessageBoxLibrary.Message.InfoMessage("结束成功！");
                string ss = "";
                foreach (string ii in orgids)
                    ss += ii + ",";
                if (string.IsNullOrEmpty(ss)) ss = "0";
                else ss = ss.Substring(0, ss.Length - 1);
                LoadData(ss);
            }

        }

        private void CheckBox_Click(object sender, RoutedEventArgs e)
        {
            CheckBox cb = sender as CheckBox;
            foreach (GuaZhiEmpModel p in DGRole.ItemsSource)
            {
                p.IsSelected = (bool)cb.IsChecked;
                if (p.IsSelected)
                {
                    if (selectedempmodel.Where(i => i.ID == p.ID).FirstOrDefault() == null)
                    {
                        selectedempmodel.Add(p);
                    }
                }
                else
                {
                    if (selectedempmodel.Where(i => i.ID == p.ID).FirstOrDefault() != null)
                    {
                        selectedempmodel.Remove(selectedempmodel.Where(i => i.ID == p.ID).FirstOrDefault());
                    }
                }
            }

        }

        void Client1_GetGuaZhiDuanLianEmpModelCompleted(object sender, GetGuaZhiDuanLianEmpModelCompletedEventArgs e)
        {
            string ss = "";
            foreach (string ii in orgids)
                ss += ii + ",";
            if (string.IsNullOrEmpty(ss)) ss = "0";
            else ss = ss.Substring(0, ss.Length - 1);
            LoadData(ss);
        }
    }
}
